package demo11;

import java.lang.reflect.Field;

/**
 * @program: qy158
 * @description:
 * @author: 闫克起2
 * @create: 2022-10-27 09:46
 **/
public class Test {
    public static void main(String[] args) throws Exception {
        Class<Teacher> teacherClass = Teacher.class;
        Teacher teacher = teacherClass.newInstance();
        System.out.println(teacher);

        //获取反射类对应的属性对象
        Field name = teacherClass.getDeclaredField("name");
        //为属性赋值-- teacher.setName(); 普通的赋值
        name.set(teacher,"刘德华"); //通过反射默认对指定属性的对象赋值
        System.out.println(teacher);

        //通过反射获取指定属性的对象值。  teacher.getName()普通获取
        Object o = name.get(teacher);
        System.out.println(o);


        Field age = teacherClass.getDeclaredField("age");
        age.setAccessible(true);//允许访问私有属性
        //因为age是一个私有属性，无法直接为私有属性赋值。
        age.set(teacher,18);
        System.out.println(teacher);

        Object o1 = age.get(teacher);
        System.out.println(o1);

    }
}
class People{
     public String address;
     private String sex;
}
class Teacher extends People{

    public String name;
    private Integer age;

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}